package org.exhibitj.operators;

import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Control;
import org.exhibitj.automation.Action;
import org.exhibitj.automation.Agent;
import org.exhibitj.automation.actions.FetchRightSideOf;
import org.exhibitj.automation.actions.PointTracker;
import org.exhibitj.operators.matchers.Matcher;

public class ComboOperator extends AbstractTextOperator {
	/** Linux appears to have a buffer of 2 pixels on top and 2 pixels on bottom */
	protected static final int OS_ITEM_HEIGHT_ADJUSTMENT = System.getProperty("os.name").toLowerCase().contains("lin")? 4: 0;
	private final Combo combo;

	public ComboOperator(ShellOperator shell, Matcher<Combo>...matchers) {
		super(shell);
		combo = shell.findWidget(Combo.class, matchers);
	}

	@Override
	protected Control getControl() {
		return combo;
	}

	@Override
	protected FetchingRunnable<String> textDisplayFetcher() {
		return new FetchingRunnable<String>() {
			@Override
			public String fetchValue() {
				LOG.info("text on combo");
				return combo.getText();
			}
		};
	}

	public void enterText(String string) {
		checkIsVisible();

		askAgentTo(typeAsSequence(string));

		shell.waitForEvents();
	}

	public void select(String text) {
		checkIsVisible();

		askAgentTo(selectItem(text));
		shell.waitForEvents();
	}

	private Action selectItem(final String text) {
		return new Action() {
			
			@Override
			public void perform(Agent agent) {
				combo.select(combo.indexOf(text));
			}
		};
	}

	protected PointTracker rightOf(Control control) {
		return new FetchRightSideOf(control);
	}
}
